package org.jeecg.modules.mes.order.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.mes.chiefdata.entity.MesPrintModel;
import org.jeecg.modules.mes.client.*;
import org.jeecg.modules.mes.order.entity.MesOrderProduce;
import org.jeecg.modules.mes.order.entity.MesProduceItem;
import org.jeecg.modules.mes.order.entity.MesProduceProcess;
import org.jeecg.modules.mes.order.service.*;
import org.jeecg.modules.mes.print.conHead;
import org.jeecg.modules.mes.print.conmap;
import org.jeecg.modules.mes.print.mesUtil;
import org.jeecg.modules.mes.storage.entity.MesLackMaterial;
import org.jeecg.modules.mes.storage.entity.MesStockManage;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 * @Description: 订单管理—生产订单
 * @Author: jeecg-boot
 * @Date: 2020-10-19
 * @Version: V1.0
 */
@Api(tags = "订单管理—生产订单")
@RestController
@RequestMapping("/order/mesOrderProduce")
@Slf4j
public class MesOrderProduceController extends JeecgController<MesOrderProduce, IMesOrderProduceService> {

    @Autowired
    private IMesOrderProduceService mesOrderProduceService;

    @Autowired
    private IMesProduceItemService mesProduceItemService;

    @Autowired
    private IMesProduceProcessService mesProduceProcessService;

    @Autowired
    BomClient bomClient;

    @Autowired
    StockClient stockClient;

    @Autowired
    WorkbillClient workbillClient;

    @Autowired
    WareHouseClient wareHouseClient;

    private ExecutorService executor = Executors.newCachedThreadPool();



    /*---------------------------------主表处理-begin-------------------------------------*/

    /**
     * 分页列表查询
     *
     * @param mesOrderProduce
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "订单管理—生产订单-分页列表查询")
    @ApiOperation(value = "订单管理—生产订单-分页列表查询", notes = "订单管理—生产订单-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(MesOrderProduce mesOrderProduce,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<MesOrderProduce> queryWrapper = QueryGenerator.initQueryWrapper(mesOrderProduce, req.getParameterMap());
        Page<MesOrderProduce> page = new Page<MesOrderProduce>(pageNo, pageSize);
//        IPage<MesOrderProduce> pageList = mesOrderProduceService.page(page, queryWrapper);
//        List<MesOrderProduce> produceList = pageList.getRecords();
//        if (produceList.size() != 0) {
//            for (MesOrderProduce produce : produceList) {
//                String state = "缺料";
//                if (produce.getState().equals(state)) {
//                    //通过生产订单id，远程调用仓库模块，获取缺料单的数据
//                    List<MesLackMaterial> lackMaterialList = stockClient.queryByOrderId(produce.getId());
//                    //如果查询不到，该生产订单的缺料数据，则证明库存充足
//                    if (lackMaterialList.size() == 0) {
//                        //修改生产订单状态
//                        produce.setState("待发料");
//                        //同时领取生产订单的料件，并添加领料清单
//                        QueryWrapper<MesProduceItem> wrapper = new QueryWrapper<>();
//                        wrapper.eq("proorder_id", produce.getId());
//                        List<MesProduceItem> produceItemList = mesProduceItemService.list(wrapper);
//                        for (MesProduceItem item : produceItemList) {
//                            //添加领料清单
//                            updateMaterielOccupy(item, produce);
//                        }
//                    }
//                }
//            }
//        }
        return mesOrderProduceService.queryPageList(page, queryWrapper);
    }


    /**
     * 手动领料
     *
     * @param id 生产订单id
     * @return
     */
    @ApiOperation(value = "订单管理—生产订单-手动锁定库存", notes = "订单管理—生产订单-手动锁定库存")
    @GetMapping(value = "/handGetMaterials")
    public Result<?> handGetMaterials(@RequestParam("id") String id) {
        MesOrderProduce produce = mesOrderProduceService.getById(id);
        String state = "缺料";
        if (produce.getState().equals(state)) {
            //通过生产订单id，远程调用仓库模块，获取缺料单的数据
            List<MesLackMaterial> lackMaterialList = stockClient.queryByOrderId(produce.getId());
            //如果查询不到，该生产订单的缺料数据，则证明库存充足
            if (lackMaterialList.size() == 0) {
                //修改生产订单状态
                produce.setState("待发料");
                //同时领取生产订单的料件，并添加领料清单
                LambdaQueryWrapper<MesProduceItem> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(MesProduceItem::getProorderId, produce.getId());
                List<MesProduceItem> produceItemList = mesProduceItemService.list(wrapper);
                for (MesProduceItem item : produceItemList) {
                    //添加领料清单
                    mesOrderProduceService.updateMaterielOccupy(item, produce);
                }
                MesOrderProduce nowproduce = mesOrderProduceService.getById(id);
                if ("待发料".equals(nowproduce.getState())) {
                    return Result.ok("锁定库存成功！");
                }
            }
        }
        return Result.error("锁定库存失败！缺料中！");
    }


    /**
     * 一键生产制令单
     *
     * @param id
     * @return
     */
    @AutoLog(value = "订单管理—生产订单-一键生产制令单")
    @ApiOperation(value = "订单管理—生产订单-一键生产制令单", notes = "订单管理—生产订单-一键生产制令单")
    @GetMapping(value = "/addInstruction")
    public Result<?> addInstruction(@RequestParam(name = "id", required = true) String id) {
        MesOrderProduce mesOrderProduce = mesOrderProduceService.getById(id);
        if (mesOrderProduce != null) {
            String ifSuccess = workbillClient.produceAddInstrution(mesOrderProduce);
            if ("一键生成制令单成功！！".equals(ifSuccess)) {
                mesOrderProduce.setState("已下制令单");
                mesOrderProduceService.updateById(mesOrderProduce);
                List<MesProduceItem> mesProduceItemList = mesProduceItemService.selectByMainId(id);
                String result = "未生成领料清单";
                if (com.epms.util.ObjectHelper.isNotEmpty(mesProduceItemList)) {
                    mesOrderProduce.setProduceItems(mesProduceItemList);
                    result = wareHouseClient.addMaterielOccupyByProduce(mesOrderProduce);
                }
                log.info("一键生产制令单addInstruction>>result>" + result);
                ifSuccess += "【" + result + "】";
            }
            return Result.ok(ifSuccess);
        } else {
            return Result.error("请先选择生产订单！");
        }
    }

    /**
     * 远程调用修改生产订单信息
     *
     * @param mesOrderProduce
     * @return
     */
    @PostMapping("/updatemesOrderProduce")
    public boolean updatemesOrderProduce(MesOrderProduce mesOrderProduce) {
        return mesOrderProduceService.updateById(mesOrderProduce);
    }

    /**
     * 生产订单-制令单打印
     *
     * @param id
     * @return
     */
    @AutoLog(value = "订单管理—生产订单-制令单打印")
    @ApiOperation(value = "订单管理—生产订单-制令单打印", notes = "订单管理—生产订单-制令单打印")
    @GetMapping(value = "/print")
    public Result<?> print(@RequestParam(name = "id", required = true) String id) {
        MesOrderProduce produce = mesOrderProduceService.getById(id);
        if (StringUtils.isBlank(produce.getProduceGrade())) {
            return Result.error("生产阶别不能为空！请检查！");
        }
        String produceGrade = produce.getProduceGrade();
        String[] pGrade = produceGrade.split(",");
        for (String s : pGrade) {
            System.err.println(s);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            String dateString = formatter.format(new Date());
            produce.setPrintTime(dateString);
            // 获取随机字符串
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
            int random = RandomUtils.nextInt(90) + 10;
            String randomNo = format.format(new Date()) + random;

            //标签打印，通过打印类型，远程调用主数据模块，获取到打印模块的数据
            String mobileType = "制令单打印";
            MesPrintModel printModel = bomClient.queryByPrintType(mobileType);
            if (printModel != null) {
                try {
                    executor.execute(new Runnable() {
                        @Override
                        public void run() {
                            //coHead打印的实体类
                            conHead conHead = new conHead();
                            //二维码字段，存放制令单id
//							 conHead.setConBy1(commandbillInfo.getId());
                            //二维码字段，存放制令单号
                            conHead.setConBy1(produce.getOrderCode());
                            //随机字符串，用于文件的命名
                            conHead.setOrderNo(randomNo);
                            conHead.setConNo(randomNo);
                            // contempPath：打印模版的url路径，一般是word文档，存在minio里
                            conHead.setContempPath(printModel.getPrintModel());
                            List<conmap> conmapList = new ArrayList<>();//打印字段
                            produce.setProduceGrade(s);
                            //将批号交易类实体转成map,以K,V形式存取
                            Map map = JSON.parseObject(JSON.toJSONString(produce), Map.class);
                            System.err.println(map);
                            //遍历Map，取到Key和Value
                            map.forEach((key, value) -> {
                                System.err.println("key=" + key + ",value=" + value);
                                //conmap 打印字段实体类
                                conmap conmap = new conmap();
                                //根据key,将打印模版的{key}转换成value
                                conmap.setConKey(key.toString());
                                conmap.setConValue(value.toString());
                                conmapList.add(conmap);
                            });
                            conHead.setConmapList(conmapList);
                            try {
                                //调用打印功能，printModel.getPrintServeaddress()为调用远程打印的服务器地址
                                mesUtil.gencontract(printModel.getPrintServeaddress(), conHead);
                            } catch (Exception e) {

                            }
                        }
                    });
                } catch (Exception e) {

                }

            } else {
                return Result.error("没有找到打印模版的数据！请检查！");
            }
        }
        return Result.ok("制令单打印成功！");
    }

    /**
     * 获取已超期为完成入库的订单
     *
     * @return
     */
    @GetMapping("/getPlanedOrderProduceList")
    public List<MesOrderProduce> getPlanedOrderProduceList() {
        List<MesOrderProduce> mesOrderProduces = mesOrderProduceService.lambdaQuery().isNotNull(MesOrderProduce::getPlanEnd).le(MesOrderProduce::getPlanEnd, new Date())
                .ne(MesOrderProduce::getState, "入库完成").list();
        return mesOrderProduces;
    }

    /**
     * 通过成品料号和线别获取生产订单信息
     *
     * @param materielCode 成品料号
     * @param lineSort     线别
     * @return
     */
    @GetMapping("/getOrderProduceList")
    public List<MesOrderProduce> getOrderProduceList(@RequestParam(name = "materielCode", required = true) String materielCode,
                                                     @RequestParam(name = "lineSort", required = true) String lineSort) {
        QueryWrapper<MesOrderProduce> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("materiel_code", materielCode);
        queryWrapper.like("line_sort", lineSort);
        /*queryWrapper.ne("produce_state","入库完成");*/
        List<MesOrderProduce> mesOrderProduces = mesOrderProduceService.list(queryWrapper);
        return mesOrderProduces;
    }


    /**
     * 添加
     *
     * @param mesOrderProduce
     * @return
     */
    @AutoLog(value = "订单管理—生产订单-添加")
    @ApiOperation(value = "订单管理—生产订单-添加", notes = "订单管理—生产订单-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody MesOrderProduce mesOrderProduce) {

        boolean mark = mesOrderProduceService.add(mesOrderProduce);
        if (mark) {
            return Result.ok("添加成功！");
        } else {
            return Result.error("添加失败！");
        }
    }


    /**
     * 编辑
     *
     * @param mesOrderProduce
     * @return
     */
    @AutoLog(value = "订单管理—生产订单-编辑")
    @ApiOperation(value = "订单管理—生产订单-编辑", notes = "订单管理—生产订单-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody MesOrderProduce mesOrderProduce) {
        String id = mesOrderProduce.getId();
        //判断物料是否发料
        boolean flag = workbillClient.getCommandBomByorderId(id);
        if (!flag) {
            return Result.error("已发料，无法操作");
        }
        QueryWrapper<MesProduceItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("proorder_id", id);
        List<MesProduceItem> produceItems = mesProduceItemService.list(queryWrapper);
        for (MesProduceItem item : produceItems) {
            if (StringUtils.isNotBlank(mesOrderProduce.getGrossAccount())) {
                // 生产订单主表，生产数量改变时，对应子表的需求数量也进行改变
                BigDecimal quantity = new BigDecimal(item.getQuantity());//用量
                BigDecimal totalNum = new BigDecimal(mesOrderProduce.getGrossAccount());//生产订单总数
                BigDecimal changeNum = quantity.multiply(totalNum);//bom的需求总量 = 用量 * 生产订单总数
                item.setRequireNum(changeNum.toString());
                mesProduceItemService.updateById(item);
                System.err.println(item.getId());
                MesLackMaterial mesLackMaterial = stockClient.getByOrderItemId(item.getId());
                //如果缺料清单不为空，则修改相应的缺料数量
                if (mesLackMaterial != null) {
                    System.err.println(mesLackMaterial);
                    BigDecimal stockNum = new BigDecimal(item.getStockNum());
                    BigDecimal newLackNum = changeNum.subtract(stockNum);
                    BigDecimal newRequirNum = newLackNum.add(stockNum);
                    mesLackMaterial.setLackNum(newLackNum.toString());
                    mesLackMaterial.setRequireNum(newRequirNum.toString());
                    String result = stockClient.myEdit(mesLackMaterial);
                    System.err.println(result);
                }
            }

        }
        mesOrderProduceService.updateById(mesOrderProduce);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "订单管理—生产订单-通过id查询")
    @ApiOperation(value = "订单管理—生产订单-通过id查询", notes = "订单管理—生产订单-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        MesOrderProduce mesOrderProduce = mesOrderProduceService.getById(id);
        if (mesOrderProduce == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(mesOrderProduce);

    }

    /**
     * 远程调用 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "订单管理—生产订单-通过id查询")
    @ApiOperation(value = "订单管理—生产订单-通过id查询", notes = "订单管理—生产订单-通过id查询")
    @GetMapping(value = "/queryBysId")
    public MesOrderProduce queryBysId(@RequestParam(name = "id", required = true) String id) {
        MesOrderProduce mesOrderProduce = mesOrderProduceService.getById(id);
        return mesOrderProduce;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "订单管理—生产订单-通过id删除")
    @ApiOperation(value = "订单管理—生产订单-通过id删除", notes = "订单管理—生产订单-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        //判断物料是否发料
        boolean flag = workbillClient.getCommandBomByorderId(id);
        if (flag) {
            try {
                mesOrderProduceService.delMain(id);
                stockClient.deleteByorderId(id, null);
                stockClient.deleteOccupyByorderId(id);
                workbillClient.deleteByPorderId(id);
                workbillClient.deleteCommandBomByorderId(id);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return Result.ok("删除成功!");
        } else {
            return Result.error("已发料，无法删除");
        }
    }

//    /**
//     * 批量删除
//     *
//     * @param ids
//     * @return
//     */
//    @AutoLog(value = "订单管理—生产订单-批量删除")
//    @ApiOperation(value = "订单管理—生产订单-批量删除", notes = "订单管理—生产订单-批量删除")
//    @DeleteMapping(value = "/deleteBatch")
//    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
//        this.mesOrderProduceService.delBatchMain(Arrays.asList(ids.split(",")));
//        return Result.ok("批量删除成功!");
//    }

    /**
     * 导出
     *
     * @return
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MesOrderProduce mesOrderProduce) {
        return super.exportXls(request, mesOrderProduce, MesOrderProduce.class, "订单管理—生产订单");
    }

    /**
     * 导入
     *
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, MesOrderProduce.class);
    }
    /*---------------------------------主表处理-end-------------------------------------*/

    /**
     * 远程调用，通过id获取生产订单的数据
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryMesProduceById")
    public MesOrderProduce queryMesProduceById(@RequestParam(name = "id", required = true) String id) {
        MesOrderProduce mesOrderProduce = mesOrderProduceService.getById(id);
        return mesOrderProduce;
    }

    /**
     * 远程调用，编辑生产订单
     *
     * @param mesOrderProduce
     * @return
     */
    @PutMapping("/editProduce")
    public String editProduce(@RequestBody MesOrderProduce mesOrderProduce) {
        mesOrderProduceService.updateById(mesOrderProduce);
        return "编辑成功";
    }

    /**
     * 远程调用，通过子表id获取生产订单子表的数据
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryMesProduceItemById")
    public MesProduceItem queryMesProduceItemById(@RequestParam(name = "id", required = true) String id) {
        MesProduceItem mesProduceItem = mesProduceItemService.getById(id);
        return mesProduceItem;
    }

    /**
     * 远程调用，通过子表id获取生产订单子表的数据
     *
     * @param orderid
     * @return
     */
    @GetMapping(value = "/queryMesProduceItemByOrderId")
    public MesOrderProduce queryMesProduceItemByOrderId(@RequestParam(name = "orderid", required = true) String orderid) {

        MesOrderProduce mesProduce = mesOrderProduceService.getById(orderid);
        QueryWrapper<MesProduceItem> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("proorder_id",orderid);
        mesProduce.setProduceItems(mesProduceItemService.list(wrapper1));
        return mesProduce;
    }

    /**
     * 远程调用，通过主表id，获取生产订单子表集合
     *
     * @param orderId
     * @return
     */
    @GetMapping(value = "/listMesProduceItemByOrderId")
    public List<MesProduceItem> listMesProduceItemByOrderId(@RequestParam(name = "orderId", required = true) String orderId) {
        QueryWrapper<MesProduceItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("proorder_id", orderId);
        List<MesProduceItem> produceItemList = mesProduceItemService.list(queryWrapper);
        return produceItemList;
    }

    /*--------------------------------子表处理-订单管理—生产订单子表-begin----------------------------------------------*/

    /**
     * 通过主表ID查询
     *
     * @return
     */
    @AutoLog(value = "订单管理—生产订单子表-通过主表ID查询")
    @ApiOperation(value = "订单管理—生产订单子表-通过主表ID查询", notes = "订单管理—生产订单子表-通过主表ID查询")
    @GetMapping(value = "/listMesProduceItemByMainId")
    public Result<?> listMesProduceItemByMainId(MesProduceItem mesProduceItem,
                                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                HttpServletRequest req) {
        QueryWrapper<MesProduceItem> queryWrapper = QueryGenerator.initQueryWrapper(mesProduceItem, req.getParameterMap());
        Page<MesProduceItem> page = new Page<MesProduceItem>(pageNo, pageSize);
        IPage<MesProduceItem> pageList = mesProduceItemService.page(page, queryWrapper);
        //获取生产订单id
        String produceId = mesProduceItem.getProorderId().replace("*", "");
        //通过生产订单id，获取生产订单数据
        MesOrderProduce mesOrderProduce = mesOrderProduceService.getById(produceId);
        //如果生产订单为缺料，则查询库存，进行判断
        if ("缺料".equals(mesOrderProduce.getState())) {
            List<MesProduceItem> mesProduceItemList = pageList.getRecords();
            if (mesProduceItemList.size() != 0) {
                for (int i = 0; i < mesProduceItemList.size(); i++) {
                    MesProduceItem mesProduceItem1 = mesProduceItemList.get(i);
                    String mCode = mesProduceItem1.getMaterielCode();// 物料料号
                    //通过料号、客户获取该物料的对应的库存数量
                    MesStockManage mesStockManage = stockClient.queryByMcodeAndClient(mCode,mesOrderProduce.getClient());
                    BigDecimal stockNum = new BigDecimal(mesStockManage.getStockNum());//库存数量
                    mesProduceItemList.get(i).setStockNum(stockNum.toString());//修改库存数量
                }
                /*for (MesProduceItem produceItem : mesProduceItemList) {

                    if (mesStockManage != null&&mesStockManage.getStockNum()!=null) {
                        BigDecimal stockNum = new BigDecimal(mesStockManage.getStockNum());//库存数量
                        produceItem.setStockNum(stockNum.toString());//修改库存数量
                       *//* mesProduceItemService.updateById(produceItem);//更新操作
                        BigDecimal requireNum = new BigDecimal(produceItem.getRequireNum());
                        BigDecimal remaninNum = stockNum.subtract(requireNum);//剩余数量= 库存数量-需求数量
                        System.err.println(remaninNum);*//*
                        //如果剩余数量小于0，则代表缺料，添加缺料数据；反之则代表库存充足，删除缺料数据
                        *//*if (remaninNum.compareTo(BigDecimal.ZERO) == -1) {
                            String pItemId = produceItem.getId();
                            MesLackMaterial lackMaterial = stockClient.getByOrderItemId(pItemId);
                            if (lackMaterial == null) {
                                BigDecimal lackNum = remaninNum.abs();//缺料数量 = 库存数量 - 需求数量
                                // 若物料不足，则添加缺料清单
                                MesLackMaterial mesLackMaterial = new MesLackMaterial();
                                BeanUtils.copyProperties(produceItem, mesLackMaterial);
                                mesLackMaterial.setId(null);//主键设置为null
                                mesLackMaterial.setCreateBy(null);//创建人置为null
                                mesLackMaterial.setCreateTime(null);//创建时间设置为null
                                mesLackMaterial.setOrderId(mesOrderProduce.getId());// 生产订单id
                                mesLackMaterial.setProduceItemid(produceItem.getId());// 生产订单子表id
                                mesLackMaterial.setOrderCode(mesOrderProduce.getOrderCode());//生产订单编号
                                mesLackMaterial.setOrderName(mesOrderProduce.getOrderName());//生产订单名称
                                mesLackMaterial.setMaterielGague(produceItem.getMaterielGauge());//物料规格
                                mesLackMaterial.setLackNum(lackNum.toString());//缺料数量
                                mesLackMaterial.setStockNum(stockNum.toString());//库存数量
                                mesLackMaterial.setUnit(produceItem.getCountUnit());//单位
                                BigDecimal needNum = stockNum.add(remaninNum);
                                mesLackMaterial.setRequireNum(needNum.toString());//库存所需达到的数量
                                stockClient.addLack(mesLackMaterial);
                            } else {
                                lackMaterial.setStockNum(stockNum + "");
                                stockClient.myEdit(lackMaterial);
                            }
                        } else {
                            stockClient.deleteByorderId(mesOrderProduce.getId(), mCode);
                        }*//*
                    }
                }*/
                //如果通过生产订单id，在缺料表里找不到数据，则改变该生产订单的状态为库存充足，反之则为缺料
               /* List<MesLackMaterial> lackMaterialList = stockClient.queryByOrderId(mesOrderProduce.getId());
                if (lackMaterialList.size() == 0) {
                    List<MesProduceItem> produceItemList = pageList.getRecords();
                    for (MesProduceItem item : produceItemList) {
                        mesOrderProduceService.updateMaterielOccupy(item, mesOrderProduce);
                    }
                } else {
                    mesOrderProduce.setState("缺料");
                    mesOrderProduceService.updateById(mesOrderProduce);
                }*/
            }
        }
        IPage<MesProduceItem> pageList1 = mesProduceItemService.page(page, queryWrapper);
        return Result.ok(pageList1);
    }

    /*--------------------------------子表处理-订单管理—生产订单子表-begin----------------------------------------------*/

    /**
     * 通过主表ID查询
     *
     * @return
     */
    @AutoLog(value = "订单管理—生产订单BOM-通过主表ID查询")
    @ApiOperation(value = "订单管理—生产订单子表-通过主表ID查询", notes = "订单管理—生产订单子表-通过主表ID查询")
    @GetMapping(value = "/listMesProduceItemBom")
    public List<?> listMesProduceItemBom(MesProduceItem mesProduceItem,
                                         HttpServletRequest req) {
        QueryWrapper<MesProduceItem> queryWrapper = QueryGenerator.initQueryWrapper(mesProduceItem, req.getParameterMap());
        Page<MesProduceItem> page = new Page<MesProduceItem>(1, 99999);
        IPage<MesProduceItem> pageList = mesProduceItemService.page(page, queryWrapper);
        return pageList.getRecords();
    }

    @AutoLog(value = "订单管理—生产订单子表-通过工序查询")
    @ApiOperation(value = "订单管理—生产订单子表-通过工序查询", notes = "订单管理—生产订单子表-通过工序查询")
    @GetMapping(value = "/listProduceOrderItem")
    public List<MesProduceItem> listProduceOrderItem(@RequestParam(name = "produceId", required = false) String produceId,
                                                     @RequestParam(name = "produceGrade", required = false) String produceGrade,
                                                     @RequestParam(name = "ifDelivery", required = false) String ifDelivery,
                                                     @RequestParam(name = "ifGlaze", required = false) String ifGlaze,
                                                     @RequestParam(name = "planNum", required = false) String planNum) {
        if (StringUtils.isNotBlank(ifDelivery)) {
            QueryWrapper<MesProduceItem> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("proorder_id", produceId).eq("if_delivery", ifDelivery);
            List<MesProduceItem> produceItemList = mesProduceItemService.list(queryWrapper);
            if (StringUtils.isNotBlank(planNum)) {
                for (MesProduceItem produceItem : produceItemList) {
                    MesOrderProduce produce = mesOrderProduceService.getById(produceId);
                    BigDecimal grossNum = new BigDecimal(produce.getGrossAccount());
                    System.err.println(grossNum);
                    BigDecimal requireNum = new BigDecimal(produceItem.getRequireNum());
                    BigDecimal planNUm = new BigDecimal(planNum);
                    BigDecimal realNum = requireNum.multiply(planNUm.divide(grossNum));
                    System.err.println(realNum);
                    produceItem.setRealNum(realNum.toString());
                    mesProduceItemService.updateById(produceItem);
                }
            }
            return produceItemList;
        } else if (StringUtils.isNotBlank(ifGlaze)) {
            QueryWrapper<MesProduceItem> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("proorder_id", produceId).eq("if_glaze", ifGlaze);
            List<MesProduceItem> produceItems = mesProduceItemService.list(queryWrapper);
            return produceItems;
        }
        QueryWrapper<MesProduceItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("proorder_id", produceId);
        List<MesProduceItem> produceItems = mesProduceItemService.list(queryWrapper);
        return produceItems;
    }

    /**
     * 添加
     *
     * @param mesProduceItem
     * @return
     */
    @AutoLog(value = "订单管理—生产订单子表-添加")
    @ApiOperation(value = "订单管理—生产订单子表-添加", notes = "订单管理—生产订单子表-添加")
    @PostMapping(value = "/addMesProduceItem")
    public Result<?> addMesProduceItem(@RequestBody MesProduceItem mesProduceItem) {
        mesProduceItemService.save(mesProduceItem);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param mesProduceItem
     * @return
     */
    @AutoLog(value = "订单管理—生产订单子表-编辑")
    @ApiOperation(value = "订单管理—生产订单子表-编辑", notes = "订单管理—生产订单子表-编辑")
    @PutMapping(value = "/editMesProduceItem")
    public Result<?> editMesProduceItem(@RequestBody MesProduceItem mesProduceItem) {
        mesProduceItemService.updateById(mesProduceItem);
        return Result.ok("编辑成功!");
    }

    @PutMapping(value = "/editProduceItem")
    public String editProduceItem(@RequestBody MesProduceItem mesProduceItem) {
        mesProduceItemService.updateById(mesProduceItem);
        return "编辑成功!";
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "订单管理—生产订单子表-通过id删除")
    @ApiOperation(value = "订单管理—生产订单子表-通过id删除", notes = "订单管理—生产订单子表-通过id删除")
    @DeleteMapping(value = "/deleteMesProduceItem")
    public Result<?> deleteMesProduceItem(@RequestParam(name = "id", required = true) String id) {
        mesProduceItemService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "订单管理—生产订单子表-批量删除")
    @ApiOperation(value = "订单管理—生产订单子表-批量删除", notes = "订单管理—生产订单子表-批量删除")
    @DeleteMapping(value = "/deleteBatchMesProduceItem")
    public Result<?> deleteBatchMesProduceItem(@RequestParam(name = "ids", required = true) String ids) {
        this.mesProduceItemService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 导出
     *
     * @return
     */
    @RequestMapping(value = "/exportMesProduceItem")
    public ModelAndView exportMesProduceItem(HttpServletRequest request, MesProduceItem mesProduceItem) {
        // Step.1 组装查询条件
        QueryWrapper<MesProduceItem> queryWrapper = QueryGenerator.initQueryWrapper(mesProduceItem, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // Step.2 获取导出数据
        List<MesProduceItem> pageList = mesProduceItemService.list(queryWrapper);
        List<MesProduceItem> exportList = null;

        // 过滤选中数据
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        } else {
            exportList = pageList;
        }

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "订单管理—生产订单子表"); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, MesProduceItem.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("订单管理—生产订单子表报表", "导出人:" + sysUser.getRealname(), "订单管理—生产订单子表"));
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }

    /**
     * 导入
     *
     * @return
     */
    @RequestMapping(value = "/importMesProduceItem/{mainId}")
    public Result<?> importMesProduceItem(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<MesProduceItem> list = ExcelImportUtil.importExcel(file.getInputStream(), MesProduceItem.class, params);
                for (MesProduceItem temp : list) {
                    temp.setProorderId(mainId);
                }
                long start = System.currentTimeMillis();
                mesProduceItemService.saveBatch(list);
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                return Result.ok("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    /*--------------------------------子表处理-订单管理—生产订单子表-end----------------------------------------------*/

    /*--------------------------------子表处理-订单管理—生产订单工序子表-begin----------------------------------------------*/

    /**
     * 通过主表ID查询
     *
     * @return
     */
    @AutoLog(value = "订单管理—生产订单工序子表-通过主表ID查询")
    @ApiOperation(value = "订单管理—生产订单工序子表-通过主表ID查询", notes = "订单管理—生产订单工序子表-通过主表ID查询")
    @GetMapping(value = "/listMesProduceProcessByMainId")
    public Result<?> listMesProduceProcessByMainId(MesProduceProcess mesProduceProcess,
                                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                   HttpServletRequest req) {
        QueryWrapper<MesProduceProcess> queryWrapper = QueryGenerator.initQueryWrapper(mesProduceProcess, req.getParameterMap());
        Page<MesProduceProcess> page = new Page<MesProduceProcess>(pageNo, pageSize);
        IPage<MesProduceProcess> pageList = mesProduceProcessService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param mesProduceProcess
     * @return
     */
    @AutoLog(value = "订单管理—生产订单工序子表-添加")
    @ApiOperation(value = "订单管理—生产订单工序子表-添加", notes = "订单管理—生产订单工序子表-添加")
    @PostMapping(value = "/addMesProduceProcess")
    public Result<?> addMesProduceProcess(@RequestBody MesProduceProcess mesProduceProcess) {
        mesProduceProcessService.save(mesProduceProcess);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param mesProduceProcess
     * @return
     */
    @AutoLog(value = "订单管理—生产订单工序子表-编辑")
    @ApiOperation(value = "订单管理—生产订单工序子表-编辑", notes = "订单管理—生产订单工序子表-编辑")
    @PutMapping(value = "/editMesProduceProcess")
    public Result<?> editMesProduceProcess(@RequestBody MesProduceProcess mesProduceProcess) {
        mesProduceProcessService.updateById(mesProduceProcess);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "订单管理—生产订单工序子表-通过id删除")
    @ApiOperation(value = "订单管理—生产订单工序子表-通过id删除", notes = "订单管理—生产订单工序子表-通过id删除")
    @DeleteMapping(value = "/deleteMesProduceProcess")
    public Result<?> deleteMesProduceProcess(@RequestParam(name = "id", required = true) String id) {
        mesProduceProcessService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "订单管理—生产订单工序子表-批量删除")
    @ApiOperation(value = "订单管理—生产订单工序子表-批量删除", notes = "订单管理—生产订单工序子表-批量删除")
    @DeleteMapping(value = "/deleteBatchMesProduceProcess")
    public Result<?> deleteBatchMesProduceProcess(@RequestParam(name = "ids", required = true) String ids) {
        this.mesProduceProcessService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 导出
     *
     * @return
     */
    @RequestMapping(value = "/exportMesProduceProcess")
    public ModelAndView exportMesProduceProcess(HttpServletRequest request, MesProduceProcess mesProduceProcess) {
        // Step.1 组装查询条件
        QueryWrapper<MesProduceProcess> queryWrapper = QueryGenerator.initQueryWrapper(mesProduceProcess, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // Step.2 获取导出数据
        List<MesProduceProcess> pageList = mesProduceProcessService.list(queryWrapper);
        List<MesProduceProcess> exportList = null;

        // 过滤选中数据
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        } else {
            exportList = pageList;
        }

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "订单管理—生产订单工序子表"); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, MesProduceProcess.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("订单管理—生产订单工序子表报表", "导出人:" + sysUser.getRealname(), "订单管理—生产订单工序子表"));
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }

    /**
     * 导入
     *
     * @return
     */
    @RequestMapping(value = "/importMesProduceProcess/{mainId}")
    public Result<?> importMesProduceProcess(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<MesProduceProcess> list = ExcelImportUtil.importExcel(file.getInputStream(), MesProduceProcess.class, params);
                for (MesProduceProcess temp : list) {
                    temp.setProorderId(mainId);
                }
                long start = System.currentTimeMillis();
                mesProduceProcessService.saveBatch(list);
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                return Result.ok("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    /*--------------------------------子表处理-订单管理—生产订单工序子表-end----------------------------------------------*/


}
